package com.su.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.su.common.R;
import com.su.dto.SetmealDto;
import com.su.pojo.Category;
import com.su.pojo.Dish;
import com.su.pojo.Setmeal;
import com.su.pojo.SetmealDish;
import com.su.service.CategoryService;
import com.su.service.DishService;
import com.su.service.SetmealDishService;
import com.su.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 套餐管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;

    /**
     * 新建套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("setmeal {}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        // setmealService.save(setmeal);
        return R.success("添加套餐成功");
    }

    /**
     * 分页查询所有套餐
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "categoryCache")
    public R<Page> getByPageWithCategory(int page, int pageSize, String name) {
        //查询套餐基本信息
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, setmealLambdaQueryWrapper);
        //查询套餐分类
        List<Setmeal> records = setmealPage.getRecords();
        Set<Long> categoryIdSet = records.stream().map(setmeal -> setmeal.getCategoryId()).collect(Collectors.toSet());
        List<Category> categoryList = categoryService.listByIds(categoryIdSet);
        Map<Long, String> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        for (Setmeal record : records) {
            Long categoryId = record.getCategoryId();
            String categoryName = categoryMap.get(categoryId);
            record.setCategoryName(categoryName);
        }
        return R.success(setmealPage);
    }

    /**
     * 根据id查询(回显修改数据)
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = "categoryCache")
    public R<SetmealDto> getById(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息和相关联菜品信息
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> updateByIdWithCategory(@RequestBody SetmealDto setmealDto) {
        setmealService.updateByIdWithCategory(setmealDto);
        return R.success("修改成功");
    }

    /**
     * 修改状态
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> updateStatus(@RequestParam List<Long> ids, @PathVariable int status) {
        LambdaUpdateWrapper<Setmeal> setmealLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        setmealLambdaUpdateWrapper.set(Setmeal::getStatus, status);
        setmealLambdaUpdateWrapper.in(Setmeal::getId, ids);
        setmealService.update(setmealLambdaUpdateWrapper);
        return R.success("修改成功");
    }

    /**
     * 删除套餐信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        boolean falg = setmealService.removeByIdsWithDish(ids);
        if (falg) {
            return R.success("删除成功");
        }
        return R.error("套餐处于起售状态，删除失败 ");
    }

    /**
     * 获取套餐信息
     *
     * @param
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "categoryCache")
    public R<List<Setmeal>> getByList(@RequestParam Long categoryId, @RequestParam int status) {
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus, status);
        setmealLambdaQueryWrapper.eq(categoryId != null, Setmeal::getCategoryId, categoryId);
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);
        return R.success(setmealList);
    }

    /**
     * 根据id查询套餐详情
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    @Cacheable(value = "categoryCache")
    public R<List<SetmealDish>> getDish(@PathVariable Long id) {
        //查询菜品信息
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(id != null, SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);

        List<Long> dishIdList = setmealDishList.stream().map(setmealDish -> setmealDish.getDishId()).collect(Collectors.toList());
        List<Dish> dishList = dishService.listByIds(dishIdList);
        Map<Long, String> map = dishList.stream().collect(Collectors.toMap(Dish::getId, Dish::getImage));

        for (SetmealDish setmealDish : setmealDishList) {
            Long dishId = setmealDish.getDishId();
            String img = map.get(dishId);
            setmealDish.setImage(img);
        }
        return R.success(setmealDishList);
    }
}
